package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SiyuCharge;
import com.ruoyi.project.system.domain.SiyuProduct;
import com.ruoyi.project.system.domain.SiyuQuery;
import com.ruoyi.project.system.domain.SiyuUserPrice;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.ISiyuQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;
import static com.ruoyi.common.utils.DateUtils.parseDateToStr;

/**
 * 进件记录Service业务层处理
 */
@Slf4j
@Service
public class SiyuQueryServiceImpl implements ISiyuQueryService {

    @Autowired
    private SiyuQueryMapper siyuQueryMapper;

    @Autowired
    private SiyuUserPriceMapper siyuUserPriceMapper;

    @Autowired
    private SiyuProductMapper siyuProductMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SiyuChargeMapper siyuChargeMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    public int setQueryinfo(Integer productId, Integer queryId, String info, Date nowDate) {
        HashMap<String, Object> queryinfo = siyuQueryMapper.selectQueryinfo(productId, queryId);
        if (queryinfo == null || queryinfo.isEmpty()) {
            return siyuQueryMapper.insertQueryinfo(queryId, productId, info, nowDate);
        } else {
            return siyuQueryMapper.updateQueryinfo(Integer.parseInt(queryinfo.get("id").toString()), info, nowDate);
        }
    }

    @Override
    @Transactional
    public AjaxResult queryData(SiyuQuery siyuQuery) {
        SiyuProduct product = siyuProductMapper.selectSiyuProductById(siyuQuery.getProductId());

        JSONObject params = new JSONObject();
        Object result = null;
        if ("syshc".equals(product.getCode())) {
            result = JSON.toJSONString(authInfoQuery(siyuQuery));
        } else if ("blxw".equals(product.getCode())) {
            params.put("cardNo", siyuQuery.getCardNo());
            result = otherInfoQuery("JF002", params);
        } else if ("graj".equals(product.getCode())) {
            params.put("name", siyuQuery.getName());
            params.put("cardNo", siyuQuery.getCardNo());
            result = otherInfoQuery("JF025", params);
        } else if ("hy".equals(product.getCode())) {
            result = JSON.toJSONString(marryQuery(siyuQuery));
        } else if ("qjld".equals(product.getCode())) {
            result = otherInfoQuery("JF027", disNCM(siyuQuery));
        } else if ("dttz".equals(product.getCode())) {
            result = otherInfoQuery("JF011", disNCM(siyuQuery));
        } else if ("sqyx".equals(product.getCode())) {
            result = otherInfoQuery("JF026", disNCM(siyuQuery));
        } else if ("tza".equals(product.getCode())) {
            result = otherInfoQuery("JF028", disNCM(siyuQuery));
        } else if ("jxzs".equals(product.getCode())) {
            result = otherInfoQuery("JF010", disNCM(siyuQuery));
        } else if ("qwdbg".equals(product.getCode())) {
            // 全维度报告
            result = allReportQuery(siyuQuery).toJSONString();
        }
        // 异步扣费
        AsyncManager.me().execute(AsyncFactory.aysFee(siyuQuery, SecurityUtils.getUserId()));
        // 写入查询结果
        Date nowDate = DateUtils.getNowDate();
        setQueryinfo(siyuQuery.getProductId(), siyuQuery.getQueryId(), result.toString(), nowDate);

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("time", parseDateToStr(YYYY_MM_DD_HH_MM_SS, nowDate));
        ajaxResult.put("info", result);
        return ajaxResult;
    }

    @Override
    public JSONObject reportQuery(JSONObject params) {
        params.put("request_sn", "TQTZ" + IdUtils.fastSimpleUUID().substring(0, 12).toUpperCase());
        params.put("req_time", System.currentTimeMillis());
        String resInfo = HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json");
        return JSON.parseObject(resInfo);
    }

    private JSONObject disNCM(SiyuQuery siyuQuery) {
        JSONObject params = new JSONObject();
        params.put("mobile", siyuQuery.getTel());
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        return params;
    }

    public JSONObject allReportQuery(SiyuQuery siyuQuery) {
        JSONObject ncmData = new JSONObject();
        ncmData.put("name", siyuQuery.getName());
        ncmData.put("cardNo", siyuQuery.getCardNo());
        ncmData.put("mobile", siyuQuery.getTel());
        CompletableFuture<HashMap<String, JSONObject>> zwsc_blxw = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject cData = new JSONObject();
                    cData.put("inter_id", "JF002");
                    cData.put("cardNo", siyuQuery.getCardNo());
                    respMap.put("blxw", reportQuery(cData));

                    JSONObject mData = new JSONObject();
                    mData.put("inter_id", "JF030");
                    mData.put("mobile", siyuQuery.getTel());
                    respMap.put("zwsc", reportQuery(mData));

                    return respMap;
                }
        );
        CompletableFuture<HashMap<String, JSONObject>> smrz_sjsys = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject ncData = new JSONObject();
                    ncData.put("inter_id", "JF005");
                    ncData.put("name", siyuQuery.getName());
                    ncData.put("cardNo", siyuQuery.getCardNo());
                    respMap.put("smrz", reportQuery(ncData));

                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF007");
                    reqData.putAll(ncmData);
                    respMap.put("sjsys", reportQuery(reqData));

                    return respMap;
                }
        );
        CompletableFuture<HashMap<String, JSONObject>> qjld_jxzs = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF027");
                    reqData.putAll(ncmData);
                    respMap.put("qjld", reportQuery(reqData));

                    JSONObject reqData_ = new JSONObject();
                    reqData_.put("inter_id", "JF010");
                    reqData_.putAll(ncmData);
                    respMap.put("jxzs", reportQuery(reqData_));

                    return respMap;
                }
        );
        CompletableFuture<HashMap<String, JSONObject>> zulin_sf = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF026");
                    reqData.putAll(ncmData);
                    respMap.put("zulin", reportQuery(reqData));

                    JSONObject reqData_ = new JSONObject();
                    reqData_.put("inter_id", "JF025");
                    reqData_.putAll(ncmData);
                    respMap.put("sf", reportQuery(reqData_));

                    return respMap;
                }
        );
        CompletableFuture<JSONObject> dq = CompletableFuture.supplyAsync(() -> {
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF011");
                    reqData.putAll(ncmData);
                    return reportQuery(reqData);
                }
        );
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(zwsc_blxw, smrz_sjsys, qjld_jxzs, zulin_sf, dq);
        allFutures.join();

        JSONObject object = new JSONObject();
        try {
            object.putAll(zwsc_blxw.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(smrz_sjsys.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(qjld_jxzs.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(zulin_sf.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("dq", dq.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public JSONObject authInfoQuery(SiyuQuery siyuQuery) {
        JSONObject result = new JSONObject();
        JSONObject params = new JSONObject();
        String baseReqSn = "TQTZ" + IdUtils.fastSimpleUUID().substring(0, 12).toUpperCase();
        params.put("req_time", System.currentTimeMillis());
        // 在网时长
        params.put("request_sn", baseReqSn + "JF030");
        params.put("inter_id", "JF030");
        params.put("mobile", siyuQuery.getTel());
        result.put("zwsc", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        // 实名认证
        params.replace("request_sn", baseReqSn + "JF005");
        params.replace("inter_id", "JF005");
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        result.put("smrz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        // 三要素
        params.replace("request_sn", baseReqSn + "JF007");
        params.replace("inter_id", "JF007");
        result.put("sys", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        return result;
    }

    @Override
    public String otherInfoQuery(String jfCode, JSONObject params) {
        String baseReqSn = "TQTZ" + IdUtils.fastSimpleUUID().substring(0, 12).toUpperCase();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", baseReqSn + jfCode);
        params.put("inter_id", jfCode);
        sysConfigMapper.addInterNum();
        return HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json");
    }

    @Override
    public JSONObject marryQuery(SiyuQuery siyuQuery) {
        JSONObject result = new JSONObject();
        JSONObject params = new JSONObject();
        String baseReqSn = "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase();
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        result.put("smrz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        // 婚姻
        params.replace("request_sn", baseReqSn + "JF032");
        params.replace("inter_id", "JF032");
        result.put("hyhy", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        return result;
    }

    public void baseFee(SiyuQuery siyuQuery, Long userId) {
        Integer chargeId = siyuChargeMapper.selectSiyuChargeId(
                siyuQuery.getQueryId(),
                siyuQuery.getProductId()
        );
        if (chargeId == null) {
            fee(siyuQuery, userId);
        }
    }

    public AjaxResult fee(SiyuQuery siyuQuery, Long userId) {
        Integer productId = siyuQuery.getProductId();
        BigDecimal balance = sysUserMapper.selectUserById(userId).getBalance();
        BigDecimal price;
        SiyuUserPrice siyuUserPrice = siyuUserPriceMapper.selectPriceByUIAadPI(userId, productId);
        if (siyuUserPrice != null) {
            price = siyuUserPrice.getPrice();
        } else {
            price = siyuProductMapper.selectSiyuProductById(productId).getUnitPrice();
        }
        if (price.floatValue() > balance.floatValue()) {
            return AjaxResult.warn("余额不足");
        }
        // 写入扣费记录
        siyuChargeMapper.insertSiyuCharge(new SiyuCharge(
                userId.intValue(),
                siyuQuery.getQueryId(),
                balance,
                price,
                balance.subtract(price),
                productId,
                siyuQuery.getAuthCode()
        ));
        return sysUserMapper.subtractBalance(userId.longValue(), price) == 1 ? AjaxResult.success() : AjaxResult.warn("异常");
    }

    /**
     * 查询进件记录
     *
     * @param queryId 进件记录主键
     * @return 进件记录
     */
    @Override
    public SiyuQuery selectSiyuQueryByQueryId(Integer queryId) {
        return siyuQueryMapper.selectSiyuQueryByQueryId(queryId);
    }


    /**
     * 新增进件记录
     *
     * @param siyuQuery 进件记录
     * @return 结果
     */
    @Override
    public int insertSiyuQuery(SiyuQuery siyuQuery) {
        return siyuQueryMapper.insertSiyuQuery(siyuQuery);
    }

    /**
     * 修改进件记录
     *
     * @param siyuQuery 进件记录
     * @return 结果
     */
    @Override
    public int updateSiyuQuery(SiyuQuery siyuQuery) {
        return siyuQueryMapper.updateSiyuQuery(siyuQuery);
    }

    /**
     * 批量删除进件记录
     *
     * @param queryIds 需要删除的进件记录主键
     * @return 结果
     */
    @Override
    public int deleteSiyuQueryByQueryIds(Integer[] queryIds) {
        return siyuQueryMapper.deleteSiyuQueryByQueryIds(queryIds);
    }

    /**
     * 删除进件记录信息
     *
     * @param queryId 进件记录主键
     * @return 结果
     */
    @Override
    public int deleteSiyuQueryByQueryId(Integer queryId) {
        return siyuQueryMapper.deleteSiyuQueryByQueryId(queryId);
    }
}
